import {reqGetCode,reqUserRegister,reqUserLogin,reqGetUserInfo,reqUserLoginout} from '@/api'
import {getUserTempId,} from '@/utils/userAbout'

const state = {
  // 初始化的时候就获取用户的临时标识存储到这里
  userTempId:getUserTempId(),
  code:'',
  // token:'', // 初始化为空串我们是做登录,如果要做自动登录,那么就要先从localStorage里面拿
  token:localStorage.getItem('TOKEN_KEY'),// 空的localStorage 返回的是null
  userInfo:{},//用户信息
}


const mutations = {
  RECEIVE_CODE(state,code){
    state.code = code
  },
  RECEIVE_TOKEN(state,token){
    state.token = token
  },
  RECEIVE_USERINFO(state, userInfo){
    state.userInfo = userInfo
  },
  RESET_TOKEN(state){
    state.token = ''
    state.userInfo = {}
  }
}


const actions = {
  async getCode({commit},phone){
    const result = await reqGetCode(phone)
    if(result.code === 200){
      commit('RECEIVE_CODE',result.data)
      return result.data
    }else{
      return Promise.reject(new Error('failed'))
    }
  },


  async userRegister({commit},userInfo){
    const result = await reqUserRegister(userInfo)
    if(result.code === 200){
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },

  async userLogin({commit},userInfo){
    const result = await reqUserLogin(userInfo)
    if(result.code === 200){
      commit('RECEIVE_TOKEN', result.data.token)
      // 想要自动登录,这里拿到的token必须往localStorage里存一次
      localStorage.setItem('TOKEN_KEY', result.data.token)
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },

  //获取用户信息
  async getUserInfo({commit}){
    const result = await reqGetUserInfo()
    if(result.code === 200){
      commit('RECEIVE_USERINFO',result.data)
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },

  // 清空token
  async resetToken({commit}){
    commit('RESET_TOKEN') // 清空state内部的token
    localStorage.removeItem('TOKEN_KEY') // 请空localStorage内部的token
  },

  // 退出登录
  async userLogout({commit, dispatch}){
    const result = await reqUserLoginout()
    if(result.code === 200){
      dispatch('resetToken')  // 在一个async里面可以dispatch另外一个async
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  }
}
const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}